using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;

using Janus.Windows.Schedule;
namespace Janus.NorthwindDemo2007
{
	public partial class AppointmentsForm
	{

		private bool mHasChanged = false;
		private TimeSpan mDuration;
		private bool mInitialized;
		private Janus.Windows.Schedule.Schedule mSchedule;
		private Janus.Windows.Schedule.ScheduleAppointment mAppointment;


		private Janus.Windows.Schedule.ScheduleAppointment Appointment
		{
			get
			{
				return mAppointment;
			}
			set
			{

				if ( mAppointment != value)
				{
					mAppointment = value;
					if (mAppointment != null)
					{
						this.AppointmentCategoriesTableAdapter1.Fill(this.dsNorthwind.AppointmentCategories);
                        //this.rcboCategory.ComboBox.Items.p
						this.mccCategories.SetDataBinding(this.dsNorthwind, "AppointmentCategories");
						this.mDuration = mAppointment.Duration;
						this.txtDescription.Text = mAppointment.Description;
						this.txtSubject.Text = mAppointment.Text;
						this.chkAllDayEvent.Checked = mAppointment.AllDayEvent;
						this.mccCategories.Value = mAppointment.GetValue("AppointmentCategoryID");
						this.SetTimePanel();
						this.PopulateReminderCombo();
						this.PopulateOwnersCombo();
						mInitialized = false;
						System.DateTime startDate = Appointment.StartTime;
						this.jsccStartDate.Value = startDate.Date;
						this.jsccEndDate.Value = startDate.Add(this.mDuration).Date;
						this.jsccStartTime.Value = startDate;
						this.jsccEndTime.Value = startDate.Add(this.mDuration);
						this.SetWarningText();
						mInitialized = true;
					}
				}
			}
		}

		public void CreateAppointmentForm(Janus.Windows.Schedule.Schedule schedule, System.DateTime startDate, TimeSpan duration, Janus.Windows.Schedule.ScheduleAppointment app)
		{
			this.mSchedule = schedule;
			if (app == null)
			{
				app = new ScheduleAppointment(startDate, startDate.Add(duration));
				if (this.mSchedule.CurrentOwner != null)
				{
					app.Owner = this.mSchedule.CurrentOwner.Value;
				}
			}
			this.Appointment = app;
			mHasChanged = false;
			this.Show();
		}

		private void PopulateReminderCombo()
		{
            this.rcboReminder.ComboBox.Items.Clear();
            rcboReminder.ComboBox.Items.Add("None", DBNull.Value);
            rcboReminder.ComboBox.Items.Add("0 minutes", new TimeSpan(0, 0, 0));
            rcboReminder.ComboBox.Items.Add("5 minutes", new TimeSpan(0, 5, 0));
            rcboReminder.ComboBox.Items.Add("10 minutes", new TimeSpan(0, 10, 0));
            rcboReminder.ComboBox.Items.Add("15 minutes", new TimeSpan(0, 15, 0));
            rcboReminder.ComboBox.Items.Add("30 minutes", new TimeSpan(0, 30, 0));
            rcboReminder.ComboBox.Items.Add("1 hour", new TimeSpan(1, 0, 0));
            rcboReminder.ComboBox.Items.Add("2 hours", new TimeSpan(2, 0, 0));
            rcboReminder.ComboBox.Items.Add("4 hours", new TimeSpan(4, 0, 0));
            if (mAppointment != null)
            {
                if (mAppointment.Reminder.Enabled)
                {
                    rcboReminder.ComboBox.SelectedIndex = 0;
                }
                else
                {
                    rcboReminder.ComboBox.SelectedValue = mAppointment.Reminder.ReminderInterval;
                }
             
            }

            //this.cboReminder.Items.Clear();
            //cboReminder.DisplayMember = "Text";
            //cboReminder.Items.Add("0 minutes", new TimeSpan(0, 0, 0));
            //cboReminder.Items.Add("5 minutes", new TimeSpan(0, 5, 0));
            //cboReminder.Items.Add("10 minutes", new TimeSpan(0, 10, 0));
            //cboReminder.Items.Add("15 minutes", new TimeSpan(0, 15, 0));
            //cboReminder.Items.Add("30 minutes", new TimeSpan(0, 30, 0));
            //cboReminder.Items.Add("1 hour", new TimeSpan(1, 0, 0));
            //cboReminder.Items.Add("2 hours", new TimeSpan(2, 0, 0));
            //cboReminder.Items.Add("4 hours", new TimeSpan(4, 0, 0));


            //if (mAppointment != null)
            //{
            //    TimeSpan time = new TimeSpan();
            //    foreach (Janus.Windows.EditControls.UIComboBoxItem reminder in cboReminder.Items)
            //    {
            //        time = (TimeSpan)reminder.Value;
            //        if (time.Equals(mAppointment.Reminder.ReminderInterval))
            //        {
            //            cboReminder.SelectedItem = reminder;
            //            return;
            //        }
            //    }
            //}
            //cboReminder.SelectedIndex = 3;
		}

		private void PopulateOwnersCombo()
		{
			this.mccOwners.DataSource = mSchedule.Owners;
			this.mccOwners.Value = mAppointment.Owner;
		}

		private void SetWarningText()
		{
			string str = string.Empty;
			this.pnlInfo.Height = 35;
			if (this.Appointment.RecurrenceState == RecurrenceState.Master)
			{
				pnlInfo.Visible = false;
				return;
			}
			else if (this.Appointment.RecurrenceState != RecurrenceState.NotRecurring)
			{
				str = "  " + NorthwindApp.GetRecurrenceInfoText(this.Appointment.RecurrencePattern) + "\r\n";
			}
			Janus.Windows.Schedule.DateRange range = new Janus.Windows.Schedule.DateRange(this.GetCompleteStartDate().AddSeconds(1), this.GetCompleteEndDate().AddSeconds(-1));
			if (range.Start < DateTime.Now)
			{

				if (str.Length > 0)
				{
					this.pnlInfo.Height += this.lblInfo.Height - 4;
					str += "  This appointment occurs in the past";
				}
				else
				{
					ScheduleAppointmentOwner owner = null;
					if (this.mccOwners.Value != null)
					{
						owner = mSchedule.Owners[this.mccOwners.Value];
					}
					ScheduleAppointment[] list = mSchedule.GetAppointmentsFromRange(range, owner);
					if (list.Length > 1 || (list.Length == 1 &&  (list[0] != mAppointment)))
					{

						if (str.Length > 0)
						{
							this.pnlInfo.Height += this.lblInfo.Height - 4;
						}
						str += "  Conflicts with another appointment in your Calendar";
					}
				}
			}
			if (str.Length == 0)
			{
				pnlInfo.Visible = false;
			}
			else
			{
				pnlInfo.Visible = true;
				lblInfo.Text = str;
			}
		}

		private void SetTimePanel()
		{
			if (this.Appointment.RecurrenceState == RecurrenceState.Master)
			{
				pnlAppointmentTime.Visible = false;
				pnlRecurrenceInfo.Visible = true;
                this.lblRecurrenceInfo.Text = NorthwindApp.GetRecurrenceInfoText(this.Appointment.RecurrencePattern);
			}
			else
			{
				pnlAppointmentTime.Visible = true;
				pnlRecurrenceInfo.Visible = false;
			}
		}

		private void SetFormText()
		{

			if (txtSubject.Text.Length > 0)
			{
				this.Text = txtSubject.Text + " - ";
			}
			else
			{
				this.Text = "Untitled - ";
			}
			if (this.chkAllDayEvent.Checked)
			{
				this.Text += "Event";
			}
			else
			{
				this.Text += "Appointment";
			}
		}



		private void DeleteAppointment()
		{
			if (mHasChanged)
			{
				DialogResult dialog = MessageBox.Show(this, "The appointment has been changed. Are you sure you want to delete it?", NorthwindApp.MessageCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
				if (dialog == System.Windows.Forms.DialogResult.No)
				{
					return;
				}
			}
			Appointment.Delete();

			this.mHasChanged = false;
			this.Close();

		}

		private void SaveAppointment(bool close)
		{
			mHasChanged = false;
			mAppointment.Move(this.GetCompleteStartDate(), this.GetCompleteEndDate());
			mAppointment.Text = this.txtSubject.Text;

			mAppointment.Owner = this.mccOwners.Value;
			mAppointment.Description = this.txtDescription.Text;
            if (this.rcboReminder.ComboBox.SelectedIndex <= 0)
            {
                mAppointment.Reminder.Enabled = false;
            }
            else
            {
                mAppointment.Reminder.Enabled = true;
                mAppointment.Reminder.ReminderInterval = (TimeSpan)rcboReminder.ComboBox.SelectedValue;
            }
            //mAppointment.Reminder.ReminderInterval = (TimeSpan)cboReminder.SelectedItem.Value;

			mAppointment.AllDayEvent = this.chkAllDayEvent.Checked;
			if (mAppointment.Schedule == null)
			{
				this.mSchedule.Appointments.Add(mAppointment);
			}
			mAppointment.SetValue("AppointmentCategoryID", this.mccCategories.Value);

            //mAppointment.Reminder.Enabled = this.chkReminder.Checked;
			if (close)
			{
				this.Close();
			}
		}

		private void AppointmentForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if (mHasChanged)
			{
				DialogResult result = MessageBox.Show(this, "Do you want to save changes", NorthwindApp.MessageCaption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);

				if (result == System.Windows.Forms.DialogResult.Yes)
				{
					this.SaveAppointment(false);
				}
				else if (result == System.Windows.Forms.DialogResult.Cancel)
				{
					e.Cancel = true;
				}
			}
		}

		private void jsccStartTime_ValueChanged(object sender, System.EventArgs e)
		{
			if (! mInitialized)
			{
				return;
			}

			System.DateTime startDate = this.GetCompleteStartDate();
			jsccEndTime.Value = startDate.Add(mDuration);
			this.SetWarningText();
			mHasChanged = true;
		}

		private void jsccStartDate_ValueChanged(object sender, System.EventArgs e)
		{

			if (! mInitialized)
			{
				return;
			}

			jsccEndDate.Value = this.GetCompleteStartDate().Add(mDuration);
			jsccStartTime.Value = this.jsccStartDate.Value.Date.Add(jsccStartTime.Value.TimeOfDay);
			mHasChanged = true;
		}

		private void jsccEndDate_ValueChanged(object sender, System.EventArgs e)
		{
			if (! mInitialized)
			{
				return;
			}

			System.DateTime startDate = this.GetCompleteStartDate();
			System.DateTime endDate = this.GetCompleteEndDate();
			if (endDate < startDate)
			{
				jsccEndTime.Value = startDate.Add(mDuration);
				jsccEndDate.Value = startDate.Add(mDuration);
			}
			else
			{
				mDuration = endDate.Subtract(startDate);
				jsccEndTime.Value = jsccEndDate.Value.Date.Add(jsccEndTime.Value.TimeOfDay);
			}
			this.SetWarningText();
			mHasChanged = true;
		}

		private void jsccEndTime_ValueChanged(object sender, System.EventArgs e)
		{
			if (! mInitialized)
			{
				return;
			}

			if (jsccEndTime.Value < jsccStartTime.Value)
			{
				jsccEndTime.Value = jsccStartTime.Value.Add(mDuration);
			}
			else
			{
				mDuration = jsccEndTime.Value.Subtract(jsccStartTime.Value);
			}
			jsccEndDate.Value = this.jsccEndTime.Value.Date;
			this.SetWarningText();
			mHasChanged = true;
		}

		private System.DateTime GetCompleteStartDate()
		{
			System.DateTime startDate = this.jsccStartDate.Value.Date;
			if (! chkAllDayEvent.Checked)
			{
				startDate = startDate.Add(this.jsccStartTime.Value.TimeOfDay);
			}
			return startDate;
		}

		private System.DateTime GetCompleteEndDate()
		{
			System.DateTime endDate = this.jsccEndDate.Value.Date;
			if (! this.chkAllDayEvent.Checked)
			{
				endDate = endDate.Add(this.jsccEndTime.Value.TimeOfDay);
			}
			return endDate;

		}

		private void value_Changed(object sender, System.EventArgs e)
		{

			mHasChanged = true;
		}

		private void chkAllDayEvent_CheckedChanged(object sender, System.EventArgs e)
		{
			this.jsccEndTime.Enabled = ! chkAllDayEvent.Checked;
			this.jsccStartTime.Enabled = ! chkAllDayEvent.Checked;
			if (mDuration.TotalDays >= 1)
			{
				mDuration = new TimeSpan((int)mDuration.TotalDays - 1, 0, mSchedule.MinuteInterval, 0);
				this.jsccStartTime.Value = this.jsccStartDate.Value.Add(mSchedule.WorkStartTime);
				this.jsccEndDate.Value = jsccStartTime.Value.Add(mDuration).Date;
			}
			this.SetFormText();
			mHasChanged = true;
		}

		

		private void txtSubject_TextChanged(object sender, System.EventArgs e)
		{
			this.SetFormText();
			mHasChanged = true;
		}



		private void cmAppointmentForm_CommandClick(object sender, Janus.Windows.UI.CommandBars.CommandEventArgs e)
		{

			switch (e.Command.Key)
			{
				case "cmdDelete":
					this.DeleteAppointment();
					break;
				case "cmdRecurrence":
					this.ShowRecurrenceForm();
					break;
				case "cmdSave":
					this.SaveAppointment(true);
					break;
			}
		}

		private void ShowRecurrenceForm()
		{
			RecurrenceForm frm = new RecurrenceForm();
			frm.ShowRecurrenceForm(this.Appointment);
			if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
			{
				if (this.Appointment.MasterAppointment != null)
				{
					this.Appointment = this.Appointment.MasterAppointment;
				}
				else
				{
					this.SetTimePanel();
					this.SetWarningText();
				}
			}
		}

		protected override void OnLoad(EventArgs e)
		{
			Janus.Windows.UI.Dock.UIPanelManager pm = new Janus.Windows.UI.Dock.UIPanelManager();
			pm.VisualStyle = Janus.Windows.UI.Dock.PanelVisualStyle.Office2003;
			this.lblInfo.BackColor = pm.GetDefaultColor(Janus.Windows.UI.Dock.PanelColors.InnerWorkspace);
			this.lblInfo.ForeColor = Color.White;
			base.OnLoad(e);
			NorthwindApp.MainForm.VisualStyleManager1.AddControl(this, true);

		}

        private void ribbon1_CommandClick(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            switch (e.Command.Key)
            {
                case "rcmdDelete":
                    this.DeleteAppointment();
                    break;
                case "rcmdRecurrence":
                    this.ShowRecurrenceForm();
                    break;
                case "rcmdSaveAndClose":
                    this.SaveAppointment(true);
                    break;
                case "rcmdCalendar":
                    ApplicationFolder folder = null;
                    folder = NorthwindApp.RootFolder.Find("Calendar");
                    if (folder != null)
                    {
                        NorthwindApp.MainForm.CurrentFolder = folder;
                    }
                    NorthwindApp.MainForm.BringToFront();
                    break;
            }
        }

	}
} //end of root namespace